package handler

import (
	"fmt"
	"github.com/xiyoufang/cloud-syncer/internal/env"
	"net/http"
)

func LogHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
		return
	}
	subscriber := func(m string) {
		_ = outputLog(w, flusher, m)
	}
	err := env.Logger().Subscribe(&subscriber)
	if err != nil {
		_, err = fmt.Fprintf(w, "data: %s\n\n", err.Error())
		flusher.Flush()
		return
	}
	lastLogs := env.Logger().GetLastLogs()
	for _, message := range lastLogs { // 先读取缓存里的日志
		err = outputLog(w, flusher, message)
	}
	select {
	case <-r.Context().Done():
		env.Logger().Unsubscribe(&subscriber)
		flusher = nil
	}
}

func outputLog(w http.ResponseWriter, flusher http.Flusher, message string) error {
	_, err := fmt.Fprintf(w, "data: %s\n\n", message)
	if err != nil {
		return err
	}
	if flusher != nil {
		flusher.Flush()
	}
	return nil
}
